<?php
namespace PsiFramework\Classes\Util\Object\Treeview;

import('Classes.Util.Object.Treeview.TreeviewNodeType');
import('Classes.Util.Object.Treeview.TreeviewNodeCollection');
import('Classes.Util.Object.CollectionElement');
import('Classes.Util.Object.ReferenceObject');

use \PsiFramework\Classes\Util\Object\Treeview\TreeviewNodeType;
use \PsiFramework\Classes\Util\Object\Treeview\TreeviewNodeCollection;
use \PsiFramework\Classes\Util\Object\CollectionElement;
use \PsiFramework\Classes\Util\Object\ReferenceObject;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The TreeviewNode class is used to Treeview Nodes
 *
 * @package Util.Object
 */
class TreeviewNode extends CollectionElement
{

    public function __construct(
        /*string*/ $value=null,
        TreeviewNodeCollection $children=null
    )
    {
        parent::__construct($value, $children);
    }

    public function appendChild(TreeviewNode $node)
    {
        if (is_null($this->_children)) {
            $this->_children = new TreeviewNodeCollection();
        }
        parent::appendChild($node);
    }

    public function serialize(/*boolean*/ $asText=true)
    {
        $node = parent::serialize(false);

        $value = null ;
        if ($this->_value instanceof ReferenceObject) {
            $value = $this->_value->serialize(false);
        } else if (is_string($this->_value)) {
            $value = $this->_value ;
        }

        if (!isNullOrEmptyString($value)) {
            $node->value = $value ;
        }

        if ($asText) {
            return json_encode($node);
        } else {
            return $node ;
        }
    }

    public function unserialize($value)
    {
        $jsonObject = new Json();
        $jsonObject->unserialize($value);

        $val = $jsonObject->getObject()->value ;
        if (is_object($val)) {
            $refObj = new ReferenceObject();
            $refObj->unserialize($val);
            $val = $refObj ;
        }
        $this->_value = $val ;

        $children = null ;
        if (isset($jsonObject->getObject()->children)) {
            $children = $jsonObject->getObject()->children ;
        }
        if (!is_null($children)) {
            $unserializedChildren = new TreeviewNodeCollection();
            $unserializedChildren->unserialize($children);
            $this->setChildren($unserializedChildren, $this);
        }
    }

}
